<template>
    <div class="wrapper">
        <div class="choose">
            <a-card style="width: 80%">
                <h1></h1>
                <a-form :model="state.query" name="basic" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }"
                    autocomplete="off" @finish="onFinish" @finishFailed="onFinishFailed" style="width: 100%;">

                    <a-form-item label="价格类型" :rules="[{ required: true, message: '请选择!' }]">
                        <a-radio-group v-model:value="state.query.marketOrInfo">
                            <a-radio value="materialCost">信息价</a-radio>
                            <a-radio value="marketPrice">市场价</a-radio>
                            <!--新增结算价和参考价选择，仅有框没有TS-->
                            <a-radio value="settledPrice">结算价</a-radio>
                            <a-radio value="referencePrice">参考价</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item label="选择地区">
                        <a-cascader v-model:value="state.query.area" :options="pcTextArr" placeholder="请选择地区"/>
                    </a-form-item>

                    <!--新增快捷区域选择，仅有框没有TS-->
                    <a-form-item label="快捷地区选择">
                        <a-checkbox-group v-model:value="state.query.areas" :options="areas"/>
                    </a-form-item>

                    <!--新增品牌选择，仅有框没有TS-->
                    <a-form-item label="品牌">
                        <a-input v-model:value="state.query.brand_name" :options="brand_name"/>
                    </a-form-item>

                    <!--
                    <a-form-item label="材料名称" name="name" style="width: 100%;">
                        <a-collapse v-model:activeKey="activeKey" style="width: 100%;">
                            <a-collapse-panel key="1" header="选择材料类型">
                                <a-space :size="[0, 8]" wrap>
                                    <a-checkable-tag v-for="(tag, index) in state.tagsData2" :key="tag"
                                        v-model:checked="state.selectTags2[index]" @change="checked => handleChange2(tag, checked)">
                                        {{ tag }}
                                    </a-checkable-tag>
                                </a-space>
                            </a-collapse-panel>
                            <a-collapse-panel key="2" header="选择子材料类型">
                                <a-space :size="[0, 8]" wrap>
                                    <a-checkable-tag v-for="(tag, index) in state.tagsData3" :key="tag"
                                        v-model:checked="state.selectTags3[index]" @change="checked => handleChange3(tag, checked)">
                                        {{ tag }}
                                    </a-checkable-tag>
                                </a-space>
                            </a-collapse-panel>
                        </a-collapse>
                    </a-form-item>
                    -->

                    <a-form-item label="材料名称" name="name" style="width: 100%;">
                        <a-input v-model:value="state.query.name" />
                    </a-form-item>

                    <!--新增材料规格选择，仅有框没有TS-->
                    <a-form-item label="材料规格" name="spec" style="width: 100%;">
                        <a-input v-model:value="state.query.spec" />
                    </a-form-item>

                    <a-form-item label="发布时间">
                        <a-date-picker :locale="locale" v-model:value="state.query.releaseTime_begin" picker = "month" format = "YYYY-MM" />
                        ----
                        <a-date-picker :locale="locale" v-model:value="state.query.releaseTime_end" picker = "month" format = "YYYY-MM" />
                    </a-form-item>

                    <!--
                    <a-form-item label="起始日期">
                        <a-date-picker :locale="locale" v-model:value="state.query.releaseTime_begin" picker = "month" format = "YYYY-MM" />
                    </a-form-item>

                    <a-form-item label="截止日期">
                        <a-date-picker :locale="locale" v-model:value="state.query.releaseTime_end" picker = "month" format = "YYYY-MM" />
                    </a-form-item>
                    -->

                    <a-form-item>
                        <a-button type="primary" html-type="submit">搜索</a-button>
                    </a-form-item>
                </a-form>
            </a-card>
        </div>
        <a-flex style="width: 80%; margin-top: 10px; margin-bottom: 10px; margin-left: 40px; font-size: 20px;">
            搜索条件：
            <a-tag class="searchTag" closable @close="closeAreaTag" v-if="state.query.area">区域：{{ state.query.area[0] }}--{{ state.query.area[1] }}</a-tag>
            <a-tag class="searchTag" closable @close="closeBrandNameTag" v-if="state.query.brandName">品牌：{{ state.query.brandName }}</a-tag>
            <a-tag class="searchTag" closable @close="closeNameTag" v-if="state.query.name">材料名称：{{ state.query.name }}</a-tag>
            <a-tag class="searchTag" closable @close="closeSpecTag" v-if="state.query.spec">材料规格：{{ state.query.spec }}</a-tag>
            <a-tag class="searchTag" closable @close="closeReleaseTime_beginTag" v-if="state.query.releaseTime_begin">起始时间：{{ state.query.releaseTime_begin }}</a-tag>
            <a-tag class="searchTag" closable @close="closeReleaseTime_endTag" v-if="state.query.releaseTime_end">截止时间：{{ state.query.releaseTime_end }}</a-tag>
            <a-button @click="closeAllTag">清空</a-button>
        </a-flex>
        <div class="platforms">
            <div class="menu">
                <a-layout-slider class="menu_sub">
                    <a-menu
                        v-model:selectedKeys="selectedKeys2"
                        v-model:openKeys="openKeys"
                        mode="inline"
                        style="height: 100%; border-radius: 10px;"
                    >
                        <a-sub-menu v-for="menu in menus" :key="menu.title_first">
                            <template #title>
                                <span>
                                    <user-outlined/>
                                    {{ menu.title_first }}
                                </span>
                            </template>
                            <a-menu-item v-for="subMenu in menu.title_second" :key="subMenu">{{ subMenu }}</a-menu-item>
                        </a-sub-menu>
                    </a-menu>
                </a-layout-slider>
            </div>
            <div class="table">
                <div class="tab">
                    <a-table :columns="state.marketOrInfo == 'materialCost' ? columnsOfInfo : columnsOfMark" 
                    :data-source="state.data" bordered style="width: 100%;" :pagination = "{showQuickJumper: true}">
                        <template #bodyCell="{ column, text, record }">
                            <template
                                v-if="column.dataIndex === 'name' || column.dataIndex === 'taxPrice' || column.dataIndex === 'noTaxPrice' || column.dataIndex === 'trend'">
                                <a @click="showModal(record.name, record.area, record.spec)">{{ text }}</a>
                            </template>
                        </template>
                        <template #title>Header</template>
                        <template #footer>Footer</template>
                    </a-table>
                </div>
            </div>
        </div>
    </div>
    <!-- 弹窗 -->
    <div>
        <a-modal :forceRender=true v-model:open="open" title="Basic Modal" @ok="handleOk" width="80%"
            :style="{ top: '20px' }">
            <div style="height: 700px; overflow: scroll; display: flex; flex-direction: column; align-items: center;">
                <div style="width: 100%; height: 500px; position: relative;">
                    <div style="width: 20%; height: 100%; position: absolute; left: 0; background-color: aqua;"></div>
                    <div id="myChart"></div>
                </div>
                <div style="width: 100%; height: 200px;">
                    <a-table :columns="columnsOfTrends" :data-source="state.dataOfTrends" bordered style="width: 100%;">
                        <template #bodyCell="{ column, text }">
                            <template v-if="column.dataIndex === 'name'">
                                <a>{{ text }}</a>
                            </template>
                        </template>
                        <template #title>Header</template>
                        <template #footer>Footer</template>
                    </a-table>
                </div>
            </div>
        </a-modal>
    </div>
    <div>
        <a-modal v-model:open="open1" title="Basic Modal" @ok="handleOk1" width="80%" :style="{ top: '20px' }">
            <div style="height: 700px; overflow: scroll; display: flex; flex-direction: column; align-items: center;">
                <div style="width: 100%; height: 500px; position: relative;">
                    <div
                        style="width: 100%; height: 100%; position: absolute; right: 0; background-color: rgb(201, 207, 207);">
                    </div>
                </div>
                <div style="width: 100%; height: 200px;">
                    <a-table :columns="columnsOfMarket" :data-source="state.dataOfMarket" bordered style="width: 100%;">
                        <template #bodyCell="{ column, text }">
                            <template v-if="column.dataIndex === 'name'">
                                <a>{{ text }}</a>
                            </template>
                        </template>
                        <template #title>Header</template>
                        <template #footer>Footer</template>
                    </a-table>
                </div>
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, watch, reactive } from 'vue'

import moment from 'moment'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import 'moment/dist/locale/zh-cn'
moment.locale('zh-cn')  
const text = `A dog is a type of domesticated animal.Known for its loyalty and faithfulness,it can be found as a welcome guest in many households across the world.`;
const activeKey = ref([])
watch(activeKey, val => {
    console.log(val)
})

const state = reactive({})

//地区复选
const areas = ['全国','华北','东北','华中','西北']

//下拉标签页
state.tagsData2 = reactive([])
state.selectTags2 = reactive([])

state.tagsData3 = reactive(['请选择材料分类'])
state.selectTags3 = reactive([])

state.query = {
    name: '',
    area: '',
    firstName: '',
    secondName: '',
    marketOrInfo: 'materialCost',
    releaseTime_begin: '',
    releaseTime_end: ''
}
state.formState = {}

const handleChange2 = (tag, checked) => {
    state.selectTags2 = state.tagsData2.map((item, key) => {
        if (tag == item) {
            state.query.firstName = tag
            state.query.secondName = ''
            return true
        }
        else return false
    })
    getSubCagegory(tag).then((res) => {
        state.tagsData3 = res.data.result.map((item, key) => {
            // return (key + 1) + ' ' + item
            return item
        })
    })
}

const handleChange3 = (tag, checked) => {
    state.selectTags3 = state.tagsData3.map((item, key) => {
        if (tag == item) {
            state.query.secondName = tag
            return true
        }
        else return false
    })
}

//表单
import {pcTextArr} from 'element-china-area-data'

//查询
const submitQuery = () => {
    queryPrice().then((res) => {
        console.log(res)
        res.data.result.records.sort((a, b) => a.name.length - b.name.length);
        state.data = res.data.result.records.map((item) => {
            if(state.query.marketOrInfo == 'materialCost'){
                return {
                name: item.name,
                spec: item.spec,
                unit: item.unit,
                taxPrice: item.taxPrice,
                noTaxPrice: item.noTaxPrice,
                taxRate: item.taxRate,
                typeName: item.typeName,
                area: item.area,
                releaseTime: item.releaseTime.slice(0, 7),
                trend: '趋势'
                }   
            }else if(state.query.marketOrInfo == 'marketPrice'){
                return {
                name: item.name,
                spec: item.spec,
                unit: item.unit,
                taxPrice: item.taxPrice,
                noTaxPrice: item.noTaxPrice,
                taxRate: item.taxRate,
                typeName: '市场价',
                area: item.area,
                releaseTime: item.releaseTime
                } 
            }
       
        })
    })
}

const onFinish = () => {
    console.log('query:', state.query)
    submitQuery()
}

const onFinishFailed = (rr) => {
    console.log(rr)
}

//中间的搜索条件Tag点击关闭时触发的事件
//点击关闭 区域Tag 时触发的事件
const closeAreaTag = (e /*:MouseEvent*/) => {
    //console.log(state.query.area)
    state.query.area = ''
    //console.log(state.query.area)
};
//点击关闭 品牌Tag 时触发的事件
const closeBrandNameTag = (e /*:MouseEvent*/) => {
    state.query.brandName = ''
};
//点击关闭 材料名称Tag 时 触发的事件
const closeNameTag = (e /*:MouseEvent*/) => {
    state.query.name = ''
};
//点击关闭 材料规格Tag 时触发的事件
const closeSpecTag = (e /*:MouseEvent*/) => {
    state.query.spec = ''
};
//点击关闭 起始日期Tag 时触发的事件
const closeReleaseTime_beginTag = (e /*:MouseEvent*/) => {
    state.query.releaseTime_begin = ''
};
//点击关闭 截止日期Tag 时触发的事件
const closeReleaseTime_endTag = (e /*:MouseEvent*/) => {
    state.query.releaseTime_end = ''
};
//点击关闭 全部Tag 时触发的事件
const closeAllTag = (e /*:MouseEvent*/) => {
    state.query.area = ''
    state.query.brandName = ''
    state.query.name = ''
    state.query.spec = ''
    state.query.releaseTime_begin = ''
    state.query.releaseTime_end = ''
}

//左侧菜单的数据
let menus = [
    {
        title_first: '00人工',
        title_second: [
            '0001综合用工',
            '005安装用工'
        ]
    },
    {
        title_first: '01黑色及有色金属',
        title_second: [
            '占位'
        ]
    }
]

//价格表格展示
state.marketOrInfo = 'materialCost'
const columnsOfInfo = [
    {
        title: '材料名称',
        dataIndex: 'name',
    },
    {
        title: '材料规格',
        dataIndex: 'spec',
    },
    {
        title: '计量单位',
        dataIndex: 'unit',
    },
    {
        title: '含税价',
        dataIndex: 'taxPrice',
    },
    {
        title: '除税价',
        dataIndex: 'noTaxPrice',
    },
    {
        title: '税率',
        dataIndex: 'taxRate',
    },
    {
        title: '价格类型',
        dataIndex: 'typeName',
    },
    {
        title: '区域',
        dataIndex: 'area',
    },
    {
        title: '发布时间',
        dataIndex: 'releaseTime',
    },
    {
        title: '趋势',
        dataIndex: 'trend',
    }
]

const columnsOfMark = [
    {
        title: '材料名称',
        dataIndex: 'name',
    },
    {
        title: '材料规格',
        dataIndex: 'spec',
    },
    {
        title: '计量单位',
        dataIndex: 'unit',
    },
    {
        title: '含税价',
        dataIndex: 'taxPrice',
    },
    {
        title: '除税价',
        dataIndex: 'noTaxPrice',
    },
    {
        title: '税率',
        dataIndex: 'taxRate',
    },
    {
        title: '价格类型',
        dataIndex: 'typeName',
    },
    {
        title: '区域',
        dataIndex: 'area',
    },
    {
        title: '发布时间',
        dataIndex: 'releaseTime',
    }
]

//弹窗
const open = ref(false)
const showModal = (name, area, spec) => {
    initChart(name, area, spec)
    open.value = true
}
const handleOk = e => {
    console.log(e)
    open.value = false
}
const open1 = ref(false)
const showModal1 = () => {
    open1.value = true
}
const handleOk1 = e => {
    console.log(e)
    open1.value = false
}

const columnsOfTrends = [
    {
        title: '发布日期',
        dataIndex: 'releaseTime',
    },
    {
        title: '地区',
        dataIndex: 'area',
    },
    {
        title: '价格指数',
        dataIndex: 'noTaxPrice',
    },
    {
        title: '环比上期',
        dataIndex: 'taxPrice',
    },
    {
        title: '环比上月',
        dataIndex: 'taxRate',
    },
    {
        title: '同比上年',
        dataIndex: 'taxRate',
    },
]

const columnsOfMarket = [
    {
        title: '产品说明',
        dataIndex: 'name',
    },
    {
        title: '供应商',
        dataIndex: 'spec',
    },
    {
        title: '实名认证',
        dataIndex: 'unit',
    },
    {
        title: '资质认证',
        dataIndex: 'taxPrice',
    },
    {
        title: '品牌',
        dataIndex: 'noTaxPrice',
    },
    {
        title: '单位',
        dataIndex: 'taxRate',
    },
    {
        title: '含税工程价',
        dataIndex: 'typeName',
    },
    {
        title: '历史价',
        dataIndex: 'area',
    },
    {
        title: '含税市场价',
        dataIndex: 'releaseTime',
    },
    {
        title: '税率',
        dataIndex: 'noTaxPrice',
    },
    {
        title: '报价时间',
        dataIndex: 'taxRate',
    },
    {
        title: '报价单',
        dataIndex: 'typeName',
    },
    {
        title: '收藏',
        dataIndex: 'area',
    },
    {
        title: '导出',
        dataIndex: 'releaseTime',
    },
    {
        title: '纠错',
        dataIndex: 'releaseTime',
    }
]

import * as echarts from 'echarts'
state.dataOfTrends = []

const initChart = (name, area, spec) => {
    const myChart = document.getElementById('myChart')
    let myEchart = echarts.init(myChart)
    myEchart.clear()
    let xData = []
    let data = []
    state.dataOfTrends = []
    queryChart(name, area, spec).then((res) => {
        console.log(res)
        res.data.result.forEach(item => {
            xData.push(item.release_time)
            // 将日期字符串转换为Date对象
            xData = xData.map(dateStr => new Date(dateStr));
            // 使用自定义的比较函数进行排序
            xData.sort((a, b) => a - b);
            // 如果需要将排序后的Date对象转换回yyyy-mm-dd格式的字符串
            xData = xData.map(date => date.toISOString().split('T')[0]);
            data.push(item.no_tax_price)
            state.dataOfTrends.push({ releaseTime: item.release_time, noTaxPrice: item.no_tax_price, area })
            state.dataOfTrends.sort((a, b) => {
                // 将日期字符串转换为Date对象
                const dateA = new Date(a.releaseTime);
                const dateB = new Date(b.releaseTime);

                // 比较日期
                return dateA - dateB;
            });

        });
        let options = {
            xAxis: {
                type: 'category',
                data: xData,
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data,
                    type: 'line'
                }
            ],
            dataZoom: [
                {
                    type: 'slider', // 使用滑动条类型
                    start: 0, // 初始显示范围的起始百分比
                    end: 100 // 初始显示范围的结束百分比
                }
            ],
        }
        console.log(1)

        myEchart.setOption(options,true)
    })
}

//请求
import http from '../utils/axios'
const getPrice = async () => {
    const price = await http.get('/cost/materialCost/list?pageSize=10000')
    return price
}

const getCategory = async () => {
    const category1 = await http.get('/cost/classification/getFirst')
    return category1
}

const getSubCagegory = async (key) => {
    const category2 = await http.get('/cost/classification/getSecond?firstName=' + key)
    return category2
}

const queryPrice = async () => {
    state.marketOrInfo = state.query.marketOrInfo
    let begin = ''
    let end = ''
    let area = ''
    if(state.query.area){
        area=state.query.area[0] + state.query.area[1]
    }
    if(state.query.releaseTime_begin){
        begin = (state.query.releaseTime_begin.$d.getYear() + 1900) + '-'
    + (state.query.releaseTime_begin.$d.getMonth() < 9 ? '0' + (state.query.releaseTime_begin.$d.getMonth() + 1) : state.query.releaseTime_begin.$d.getMonth() + 1)
    }
    if(state.query.releaseTime_end){
        end = (state.query.releaseTime_end.$d.getYear() + 1900) + '-'
    + (state.query.releaseTime_end.$d.getMonth() < 9 ? '0' + (state.query.releaseTime_end.$d.getMonth() + 1) : state.query.releaseTime_end.$d.getMonth() + 1)
    }

    const price = await http.get('/cost/' + state.query.marketOrInfo + '/list?name=*' + state.query.name + '*&area=' + area 
        + '&firstName=' + state.query.firstName + '&secondName=' + state.query.secondName + '&releaseTime_begin='+ begin
        + '-01&releaseTime_end=' + end + '-01&pageSize=10000')
    return price
}

const queryChart = async (name, area, spec) => {
    const chartData = await http.get('/cost/materialCost/getPoint?name=' + name + '&area=' + area + '&spec=' + spec)
    return chartData
}

//路由操作
import { useRoute } from 'vue-router'
const route = new useRoute()

//挂载时
import { onMounted } from 'vue'
onMounted(() => {
    console.log(pcTextArr)
    if (route.query) {
        console.log(route.query)
        state.firstName = route.query.firstName
        state.secondName = route.query.secondName
    }
    getCategory().then((res) => {
        state.tagsData2 = res.data.result.map((item, key) => {
            // return (key + 1) + ' ' + item
            return item
        })
    })
    getPrice().then((res) => {
        state.data = res.data.result.records.map((item) => {
            return {
            name: item.name,
            spec: item.spec,
            unit: item.unit,
            taxPrice: item.taxPrice,
            noTaxPrice: item.noTaxPrice,
            taxRate: item.taxRate,
            typeName: item.typeName,
            area: item.area,
            releaseTime: item.releaseTime.slice(0, 7),
            trend: '趋势'
            }   
        })
        console.log(state.data)
    })
})
</script>

<style scoped>
.wrapper {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.choose {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 10px;
    padding: 10px;
}

.table {
    position: relative;
    width: 80%;
    margin: 10px;
    display: flex;
    align-items: center;
    flex-direction: row;
}

.left {
    width: 30%;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.right {
    position: absolute;
    width: 70%;
    top: 0;
    right: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.tab {
    width: 100%;
    top: 0;
    right: 0;
    width: 100%;
}

#myChart {
    width: 64vw;
    height: 500px;
    position: absolute;
    right: 0;
}

.searchTag {
    border-color: red;
    font-size: 15px;
    padding: 5px;
}

.platforms {
    display: flex;
    width: 80%;
}

.menu {
    width: 20%;
    margin: 10px;
}

.menu_sub {
    overflow: auto;
}
</style>